﻿namespace EyeOpen.Combinatorics.Mvc.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Web.Mvc;

	public static class ControllerExtensions
	{
		private static readonly IDictionary<Type, TypeConverter> converterDictionary =
			new Dictionary<Type, TypeConverter>
				{
					{ typeof(int), new Int32Converter() },
					{ typeof(string), new StringConverter() },
					{ typeof(bool), new BooleanConverter() }
				};

		public static string QueryString(this Controller controller, string parameterName)
		{
			return QueryString<string>(controller, parameterName);
		}

		/// <exception cref="NotSupportedException">Cannot find the TypeConverter for type "{0}".</exception>
		public static T QueryString<T>(this Controller controller, string parameterName)
		{
			var value = controller.Request.QueryString[parameterName];

			var type = typeof(T);

			if (!converterDictionary.ContainsKey(type))
			{
				throw new NotSupportedException(string.Format("Cannot find the TypeConverter for type \"{0}\". Add it to the converterDictionary.", type));
			}

			return
				(T)converterDictionary[type]
				   	.ConvertFromString(value);
		}
	}
}